<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="开单手机" prop="openPhonenumber">
        <el-input
          v-model="queryParams.openPhonenumber"
          placeholder="请输入开单手机"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员手机" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入会员手机"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          filterable
          placeholder="选择门店"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.storeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button type="primary" size="mini" @click="handleAdd"
          >新建</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="postList">
      <el-table-column
        label="订单编号"
        align="center"
        prop="orderCode"
        width="200"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员昵称" align="center" prop="memberName">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.memberName) }}
        </template>
      </el-table-column>
      <el-table-column label="会员手机" align="center" prop="phonenumber">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.phonenumber) }}
        </template>
      </el-table-column>
      <el-table-column label="商品种类" align="center">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.goodsCate) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? "待兑现" : "已兑现" }}
        </template>
      </el-table-column> -->
      <el-table-column label="购买总数" align="center" prop="payNum">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.payNum) }}
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="orderMoney">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.orderMoney) }}
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center" prop="storeName" />
      <el-table-column
        label="开单员手机"
        align="center"
        prop="openPhonenumber"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >查看明细</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="新建销售单"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        inline
      >
        <el-form-item label="归属门店" prop="storeId">
          <el-select v-model="form.storeId" :disabled="disabled">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员手机" prop="phonenumber">
          <el-input
            ref="phoneInput"
            v-model="form.phonenumber"
            placeholder="请输入会员手机"
            maxlength="11"
            @blur="getUser"
            @keydown.enter.native="getUser"
          />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="销售商品" class="dhsf">
              <el-button
                ref="selectProductBtn"
                type="primary"
                @click="openSelectProduct"
                size="mini"
                >选择商品</el-button
              >
              <el-table ref="productTable" :data="selectProductList">
                <el-table-column label="商品">
                  <template slot-scope="scope">
                    <div class="flex items-center">
                      <el-image
                        style="width: 40px; height: 40px; margin-right: 12px"
                        :src="scope.row.goodsPhoto"
                        fit="cover"
                      ></el-image>
                      {{ scope.row.goodsName }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="goodsSpecName" label="商品规格名称" />
                <el-table-column label="销售数量" width="100">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.payNum"
                      placeholder="请输入"
                      v-number-input
                      @keyup.enter.native="openSelectProduct"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  :prop="noUserInfo == true ? 'memberMoney' : 'retailPrice'"
                  label="单价"
                />
                <el-table-column label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleRemove(scope.row)"
                      >移除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <div class="left">
          商品总数：{{ selectProductList.length }}，小计￥
          {{ subtotal }}，余额￥{{
            userInfo.accountBalance == null ? 0 : userInfo.accountBalance
          }}， 抵扣￥{{ deduction }}，实付￥
          {{ actualPayment }}
        </div>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="查看明细"
      :visible.sync="viewDetails"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table :data="detailsList">
        <el-table-column label="商品" align="center" prop="stockType" />
        <el-table-column label="销售数量" align="center" prop="detailNum">
          <template slot-scope="scope">
            {{ formatTableValue(scope.row.detailNum) }}
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="money" />
      </el-table>
      <div class="mxShop">
        商品总数：{{ shopDetails.allNum }}，小计￥
        {{ shopDetails.allMoney }}，余额抵扣￥{{
          shopDetails.amountDedu
        }}，<span class="sf">实付￥ {{ shopDetails.amount }}</span>
      </div>
    </el-dialog>
    <!-- 选择商品弹窗 -->
    <select-goods
      ref="selectProductRef"
      :selectProductList="selectProductList"
      @handle-select="handleSelectProduct"
    ></select-goods>
  </div>
</template>

<script>
import {
  getStoreOpenAPI,
  addStoreOpenAPI,
  getMemberList,
  systemStockList,
  systemStockListId,
} from "@/api/system/member";
import { getStoreList } from "@/api/system/store";
import SelectGoods from "@/components/Product/SelectGoods.vue";
import { formatDate } from "@/utils/index";
import { mapGetters } from "vuex";
export default {
  name: "mallAfterSalesManagement",
  dicts: ["sys_normal_disable"],
  components: {
    SelectGoods,
  },
  computed: {
    ...mapGetters(["roles", "storeId"]),
    // 小计
    subtotal() {
      return this.selectProductList.reduce((total, item) => {
        const price =
          this.noUserInfo == true
            ? parseFloat(item.memberMoney)
            : parseFloat(item.retailPrice) || 0;
        const quantity = parseFloat(item.payNum) || 0;
        return total + price * quantity;
      }, 0);
    },
    // 抵扣
    deduction() {
      const hasEmptyPayNum = this.selectProductList.some(
        (item) => !item.payNum || item.payNum <= 0
      );
      if (this.selectProductList.length > 0) {
        if (hasEmptyPayNum) {
          return 0;
        } else {
          // 商品总价 * 会员抵扣比例
          const payment =
            this.subtotal * (Number(this.userInfo.payProportion) / 100);
          return Math.max(0, payment).toFixed(2);
        }
      } else {
        return 0;
      }
    },
    // 实付
    actualPayment() {
      const hasEmptyPayNum = this.selectProductList.some(
        (item) => !item.payNum || item.payNum <= 0
      );
      if (this.selectProductList.length > 0) {
        if (hasEmptyPayNum) {
          return 0;
        } else {
          const payment = this.subtotal - this.deduction;
          return Math.max(0, payment).toFixed(2);
        }
      } else {
        return 0;
      }
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 1,
      // 表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        openPhonenumber: undefined,
        phonenumber: undefined,
        storeId: undefined,
        startDate: undefined,
        endDate: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: "归属门店不能为空", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "会员手机不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      viewDetails: false, // 查看明细
      detailsList: [], // 明细列表数据
      goodList: [],
      addGoods: false, // 新增商品
      goodsList: [], // 商品列表数据
      formGoods: {},
      dateRange: [],
      disabled: false,
      options: [],
      selectProductList: [],
      userInfo: {
        accountBalance: 0,
      },
      noUserInfo: false,
      shopDetails: {},
    };
  },
  watch: {
    dateRange: {
      handler(newVal, oldVal) {
        if (newVal != null && newVal.length > 0) {
          this.queryParams.startDate = newVal[0];
          this.queryParams.endDate = newVal[1];
        } else {
          this.queryParams.startDate = undefined;
          this.queryParams.endDate = undefined;
        }
      },
    },
  },
  created() {
    console.log(this.storeId);
    if (this.storeId != null) {
      this.queryParams.storeId = this.storeId;
    }
    this.getList();
    this.getStore();
    document.addEventListener("keydown", this.handleGlobalEnter);
  },
  methods: {
    handleGlobalEnter(event) {
      const isInput =
        ["INPUT", "TEXTAREA", "DIV"].includes(event.target.tagName) ||
        event.target.isContentEditable;

      if (this.open == true && event.key === "Enter" && !isInput) {
        this.openSelectProduct();
      }
    },
    getUser() {
      const phonePattern = /^1[3-9]\d{9}$/;
      if (!phonePattern.test(this.form.phonenumber)) {
        return;
      }
      getMemberList({ phonenumber: this.form.phonenumber }).then((res) => {
        if (res.code == 200) {
          if (res.rows.length == 0) {
            this.$modal.msgWarning("当前手机号不是会员");
            this.noUserInfo = false;
            this.userInfo = {
              accountBalance: 0,
              payProportion: 0,
            };
          } else {
            this.noUserInfo = true;
            this.userInfo = res.rows[0];
          }
        }
      });
    },
    getStore() {
      getStoreList().then((response) => {
        this.options = response.rows;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    openSelectProduct() {
      const phonePattern = /^1[3-9]\d{9}$/;
      if (this.form.phonenumber == null || this.form.phonenumber == "") {
        this.$modal.msgError("会员手机号码必填");
        return;
      }

      // 验证所有商品的销售数量是否大于0
      const hasInvalidPayNum = this.selectProductList.some(
        (item) => !item.payNum || item.payNum <= 0
      );
      if (hasInvalidPayNum) {
        this.$modal.msgWarning("销售数量必须大于0");
        return;
      }
      this.$refs.selectProductRef.openSelectProduct();
    },
    handleSelectProduct(row) {
      console.log(row, "选择了");
      this.selectProductList.push(...row);
      this.$refs.selectProductRef?.close();
      // 定位光标到新添加商品的销售数量输入框
      this.$nextTick(() => {
        const tableWrapper = this.$refs.productTable?.$el;
        if (tableWrapper) {
          const inputs = tableWrapper.querySelectorAll(".el-input__inner");
          const lastInput = inputs[inputs.length - 1];
          if (lastInput) {
            lastInput.focus();
            lastInput.select();
          }
        }
      });
      this.$refs.selectProductRef.subErrKeys();
    },
    handleRemove(row) {
      const matchIndex = this.selectProductList.findIndex(
        (item) => item.id === row.id
      );
      this.selectProductList.splice(matchIndex, 1);
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      getStoreOpenAPI(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: undefined,
        phonenumber: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      console.log(this.roles);
      this.selectProductList = [];
      // 店长登录自动获取门店
      if (this.storeId != null) {
        this.form.storeId = this.storeId;
        this.$nextTick(() => {
          this.$refs.phoneInput.focus();
        });
      }
      // this.disabled = this.roles.some((item) => {
      //   return item != "admin";
      // });
    },
    /** 查看明细按钮操作 */
    handleUpdate(row) {
      this.viewDetails = true;
      this.detailsList = [];
      this.shopDetails = {
        allNum: 0,
        allMoney: 0,
        amountDedu: 0,
        amount: 0,
      };
      systemStockListId({
        storeStockId: row.orderCode,
        phoneNumber: row.phonenumber,
      }).then((res) => {
        if (res.code == 200) {
          this.detailsList = res.data;
          this.shopDetails = res.resAmount;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.selectProductList?.length == 0) {
            this.$modal.msgError("请选择商品");
            return;
          }
          // 新增校验：检查payNum是否为空
          const hasEmptyPayNum = this.selectProductList.some(
            (item) => !item.payNum || item.payNum <= 0
          );
          if (hasEmptyPayNum) {
            this.$modal.msgError("请填写所有商品的销售数量,并且必须大于0");
            return;
          }
          this.form.sysMemberVoList = this.selectProductList;

          addStoreOpenAPI(this.form).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            }
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/storeOpen/export",
        {
          ...this.queryParams,
        },
        `门店开单_${formatDate(new Date())}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.left {
  float: left;
  text-align: left;
}

.dhsf {
  width: 100% !important;

  ::v-deep.el-form-item__content {
    width: 100% !important;
  }
}
.mxShop {
  margin-top: 10px;
  .sf {
    color: #ff6804;
  }
}
</style>